import { Injectable } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import moment from 'moment';

@Injectable({ providedIn: 'root' })
export class FormUtils extends FormBuilder {
	validate(form: any) {
		for (const key in form.controls) {
			const element = form.get(key);

			element.markAsDirty();
			element.updateValueAndValidity();

			if (element.length > 0) {
				for (let i = 0; i < element.length; i++) {
					this.validate(element.at(i));
				}
			}
		}
		return form.valid;
	}

	toUpper(e) {
		const v = String(e.value ? e.value : '').toLocaleUpperCase();
		if (e.value !== v) {
			e.setValue(v);
		}
		return true;
	}

	formatter(e) {
		if (e.value) {
			const v = moment(e.value).format('YYYY-MM-DD');

			if (v !== e.value) {
				e.setValue(v);
			}
		}
		return true;
	}
}
